//
//  PhotoBrowearViewController.swift
//  我的微博练习
//
//  Created by zhangguo on 15/10/23.
//  Copyright © 2015年 zhangguo. All rights reserved.
//

import UIKit
import SVProgressHUD

//可从用cell
private let GFPhotoBrowearViewCell = "GFPhotoBrowearViewCell"
class PhotoBrowearViewController: UIViewController {
 
    
    //属性    数组
    var urls: [NSURL]
    
    //用户当前选中的照片索引值
    var selectedIndex: Int
    
    init(urls:[NSURL],index:Int) {
        
        self.urls = urls
        selectedIndex = index
        
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //关闭界面
    func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //保存图片
    func save () {
        print(__FUNCTION__)
        
        //获取图片
        let indexPath = collectionView.indexPathsForVisibleItems().last!
        let cell = collectionView.cellForItemAtIndexPath(indexPath) as! PhotoBrowearViewCell
        //要判断是图像视图中是否有图像，sdw 不一定能下载到图像
        guard let image = cell.imageView.image else {
            return
        }
        
        //保存方法
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
    }
    
    func image(image:UIImage,didFinishSavingWithError error: NSError?,contextInfo: AnyObject?) {
        print(error)
        print(image)
        
        let msg = (error == nil) ? "保存成功！" : "保存失败"
        SVProgressHUD.showInfoWithStatus(msg)
    }
    
    //视图跳转之前就运行了这个方法
    override func viewDidLayoutSubviews() {
        //跳转到用户指定的图片
        let indexPath = NSIndexPath(forItem: selectedIndex, inSection: 0)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
    }
    
    //构造函数
    override func loadView() {
        
        var screenBounds = UIScreen.mainScreen().bounds
        screenBounds.size.width += 20
        
        view = UIView(frame: screenBounds)
        
        setupUI()
    }
    
   private func setupUI() {
        
        //添加控件
        view.addSubview(collectionView)
        view.addSubview(closeButton)
        view.addSubview(saveButton)
    
    //设置控件位置
    collectionView.frame = view.bounds
    
    let rect = CGRect(x: 0, y: UIScreen.mainScreen().bounds.height - 40, width: 100, height: 32)
    closeButton.frame = CGRectOffset(rect, 8, 0)
    saveButton.frame = CGRectOffset(rect, UIScreen.mainScreen().bounds.width - rect.width - 8, 0)
    
    //监听方法
    closeButton.addTarget(self, action: "close", forControlEvents: UIControlEvents.TouchUpInside)
    saveButton.addTarget(self, action: "save", forControlEvents: UIControlEvents.TouchUpInside)
    
        //独立视图
        preparCollectionView()
    }
    
    //准备collectionView
    private func preparCollectionView() {
        collectionView.registerClass(PhotoBrowearViewCell.self, forCellWithReuseIdentifier: GFPhotoBrowearViewCell)
        collectionView.dataSource = self
        
        //设置布局
        let layout = collectionView.collectionViewLayout as!UICollectionViewFlowLayout
        
        //collectionView的大小同样会宽20
        layout.itemSize = view.bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        collectionView.pagingEnabled = true
        
    }
    
    // MARK: - 懒加载
    private lazy var collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())
    
    private lazy var closeButton: UIButton = UIButton(title: "关闭", fontSize: 14, color: UIColor.whiteColor(), backColor: UIColor.darkGrayColor())
    private lazy var saveButton: UIButton = UIButton(title: "保存", fontSize: 14, color: UIColor.whiteColor(), backColor: UIColor.darkGrayColor())
    
    //图片缩放比例
    private var photoScale: CGFloat = 1
}


//数据源方法
extension PhotoBrowearViewController: UICollectionViewDataSource,PhotoBrowserCellDelegate {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return urls.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(GFPhotoBrowearViewCell, forIndexPath: indexPath) as!PhotoBrowearViewCell
        
//      cell.backgroundColor = UIColor.blackColor()
        cell.imageURLS = urls[indexPath.item]
        cell.photoDelegate = self
        return cell
    }

    //实现了转场动画代理方法
    func photoCellDidZoom(scale: CGFloat) {
        photoScale = scale
        
        //设置控件隐藏
        hideControls(scale < 1)
        //开始转场
        if scale < 1.0 {
           startInteractiveTransition(self)
        }else {
            view.transform = CGAffineTransformIdentity
            view.alpha = 1
        }
    }
    
    //完成缩放
    func photoCellDidEndZoom() {
        if photoScale < 0.8 {
            completeTransition(true)
        } else {
            UIView.animateWithDuration(0.25, animations: { () -> Void in
                
                self.view.transform = CGAffineTransformIdentity
                self.view.alpha = 1.0
                
                }, completion: { (_) -> Void in
                    
                    self.photoScale = 1
                    self.hideControls(false)
            })
        }
    }
    
    //当前选中的索引
    func currentImageIndex() -> NSIndexPath {
        
        return collectionView.indexPathsForVisibleItems().last!
        
    }
    //当前选中的imageView
    func currentImageView() -> UIImageView {
        
        let cell = collectionView.cellForItemAtIndexPath(currentImageIndex()) as! PhotoBrowearViewCell
        return cell.imageView
    } 

    //隐藏控件
    private func hideControls(hidden: Bool) {
        
        saveButton.hidden = hidden
        closeButton.hidden = hidden
        
        collectionView.backgroundColor = hidden ? UIColor.clearColor() : UIColor.blackColor()
    }
}

//遵守协议
extension PhotoBrowearViewController: UIViewControllerInteractiveTransitioning {
    
    func startInteractiveTransition(transitionContext: UIViewControllerContextTransitioning) {
        //设置形变
        view.transform = CGAffineTransformMakeScale(photoScale, photoScale)
        //设置透明度
        view.alpha = photoScale
        
    }
}

extension PhotoBrowearViewController: UIViewControllerContextTransitioning {
    //结束转场动画
     func completeTransition(didComplete: Bool){
    dismissViewControllerAnimated(true, completion: nil)
    }
    //容器视图
    func containerView() -> UIView? {return view.superview}

    func isAnimated() -> Bool {return true}
    
    func isInteractive() -> Bool{return true}
    
    func transitionWasCancelled() -> Bool{return true}
    
    func presentationStyle() -> UIModalPresentationStyle{return UIModalPresentationStyle.Custom}
    
    func updateInteractiveTransition(percentComplete: CGFloat){}
    
    func finishInteractiveTransition(){}
    
    func cancelInteractiveTransition(){}

    func viewControllerForKey(key: String) -> UIViewController?{return nil}
    
    func viewForKey(key: String) -> UIView?{return nil}
    
    func targetTransform() -> CGAffineTransform{return CGAffineTransformIdentity}
    
    func initialFrameForViewController(vc: UIViewController) -> CGRect{return CGRectZero}
  
    func finalFrameForViewController(vc: UIViewController) -> CGRect{return CGRectZero}

}
